package com.malphi.framework.core.xmlparse;

import java.io.File;
import java.util.Map;

import com.malphi.framework.core.xmlconfig.Config;
import com.malphi.framework.core.xmlconfig.XmlConfig;
import com.thoughtworks.xstream.XStream;

/******************************************************
 * 解析规则
 * 1. 节点名和属性名相同
 * 2. 引入类中所有对象做别名
 * 
 * 
 * 
 ******************************************************/

/**
 * http://xstream.codehaus.org/tutorial.html
 * config文件解析类
 * @author mrf
 * 
 */
public class ConfigParser {

    /**
     * 根据config取对应的stream
     * @param config
     * @return
     */
    private static XStream getStream(Config config){
        XStream stream = new XStream();
        XmlConfig xmlConfig = null;
        try {
            xmlConfig = config.getConfigClass().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
	    for (Map.Entry<String,Class> entry : xmlConfig.getClassMap().entrySet()) {
            stream.alias(entry.getKey(), entry.getValue());
        }
	    return stream;
	}
	
	/**
	 * xml to javabean
	 * @param stream
	 * @param xml
	 * @return
	 */
	private static Object xml2Bean(XStream stream,String xml) {
	    File file = new File(Config.CONFIG_PATH +xml);
		return stream.fromXML(file);
	}

    /**
     * 根据config生成xmlconfig bean
     * @param config
     * @return
     */
    public static XmlConfig getConfig(Config config) {
        XStream stream = getStream(config);
        return (XmlConfig) xml2Bean(stream,config.getXmlFile());
    }
}